<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小区物业管理系统 - 业主管理</title>
    <!-- Tailwind CSS v3 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <!-- 统一的 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                     primary: '#1e40af',
                     secondary: '#3b82f6',
                     accent: '#60a5fa',
                     light: '#f3f4f6',
                     dark: '#1e293b'
                 },
                 fontFamily: {
                     sans: ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }

     // 关闭查看业主模态框
     const modal = document.getElementById('view-owner-modal');
     const closeBtn = document.getElementById('close-view-owner');
     
     // 确保模态框和关闭按钮都存在
     if (modal && closeBtn) {
         // 为关闭按钮添加点击事件监听器
         closeBtn.addEventListener('click', () => {
             modal.classList.add('hidden');
         });
         
         // 为背景遮罩添加点击事件监听器
         modal.addEventListener('click', (e) => {
             // 检查是否点击了背景遮罩本身
             if (e.target === modal) {
                 modal.classList.add('hidden');
             }
         });
     }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-blue {
                background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
            .card {
                @apply bg-white rounded-md shadow-sm border border-gray-100;
            }
            .card-header {
                @apply p-4 border-b border-gray-100 font-medium text-gray-700 flex items-center justify-between;
            }
            .card-body {
                @apply p-4;
            }
            .nav-link {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-blue-50 hover:text-blue-600 rounded-md transition-all-300;
            }
            .nav-link.active {
                @apply bg-blue-50 text-blue-600;
            }
            .nav-link i {
                @apply mr-3;
            }
            .btn {
                @apply px-4 py-2 rounded-md font-medium transition-all-300 focus:outline-none focus:ring-2 focus:ring-offset-2;
            }
            .btn-primary {
                @apply bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500;
            }
            .btn-outline {
                @apply border border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-gray-500;
            }
            .btn-sm {
                @apply px-3 py-1 text-sm;
            }
            .badge {
                @apply px-2 py-1 text-xs font-medium rounded-full;
            }
            .badge-success {
                @apply bg-green-100 text-green-800;
            }
            .badge-warning {
                @apply bg-yellow-100 text-yellow-800;
            }
            .badge-danger {
                @apply bg-red-100 text-red-800;
            }
            .badge-info {
                @apply bg-blue-100 text-blue-800;
            }
            .table-row-hover {
                @apply hover:bg-gray-50 transition-all-300;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="flex h-screen overflow-hidden">
        <!-- 侧边导航栏 -->
        <aside class="w-64 bg-white shadow-sm hidden md:block">
            <!-- Logo -->
            <div class="flex items-center justify-center h-16 border-b border-gray-100">
                <div class="flex items-center">
                    <img src="https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/c70bc843c62648c5ac1442b15138cda2~tplv-a9rns2rl98-image.image?rcl=20251027174223B6A1FC2217E476B2DCF3&rk3s=8e244e95&rrcfp=f06b921b&x-expires=1764150165&x-signature=fvtwF014Si8DyDXCBMppvkase%2BI%3D" 
                         alt="Property Management System Logo" 
                         class="w-8 h-8 mr-2">
                    <span class="text-lg font-semibold text-gray-800">物业管理系统</span>
                </div>
            </div>
            
            <!-- 导航菜单 -->
            <nav class="p-4 space-y-1">
                <a href="dashboard.html" class="nav-link" data-target="dashboard-section">
                    <i class="fa fa-dashboard"></i>
                    <span>控制面板</span>
                </a>
                <a href="community.html" class="nav-link" data-target="community-section">
                    <i class="fa fa-building"></i>
                    <span>小区管理</span>
                </a>
                <a href="owners.html" class="nav-link active" data-target="owners-section">
                    <i class="fa fa-users"></i>
                    <span>业主管理</span>
                </a>
                <a href="users.html" class="nav-link" data-target="users-section">
                    <i class="fa fa-user-circle"></i>
                    <span>用户管理</span>
                </a>
                <a href="maintenance.html" class="nav-link" data-target="maintenance-section">
                    <i class="fa fa-wrench"></i>
                    <span>报修管理</span>
                </a>
                <a href="announcements.html" class="nav-link" data-target="announcements-section">
                    <i class="fa fa-bullhorn"></i>
                    <span>公告管理</span>
                </a>
                <a href="fee_management.html" class="nav-link" data-target="fee-management-section">
                    <i class="fa fa-credit-card"></i>
                    <span>物业收费管理</span>
                </a>
                <a href="settings.html" class="nav-link" data-target="settings-section">
                    <i class="fa fa-cog"></i>
                    <span>系统设置</span>
                </a>
            </nav>
        </aside>
        
        <!-- 主内容区域 -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- 顶部导航栏 -->
            <header class="bg-white shadow-sm z-10">
                <div class="flex items-center justify-between h-16 px-6">
                    <!-- 移动端菜单按钮 -->
                    <button id="mobile-menu-button" class="md:hidden text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-bars"></i>
                    </button>
                    
                    <!-- 搜索框 -->
                    <div class="flex-1 max-w-md ml-4 md:ml-8">
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                <i class="fa fa-search text-gray-400"></i>
                            </span>
                            <input type="text" placeholder="搜索..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                    </div>
                    
                    <!-- 用户菜单 -->
                    <div class="flex items-center space-x-4">
                        <!-- 通知 -->
                        <button class="relative text-gray-500 hover:text-gray-700 focus:outline-none">
                            <i class="fa fa-bell"></i>
                            <span class="absolute top-0 right-0 h-2 w-2 bg-red-500 rounded-full"></span>
                        </button>
                        
                        <!-- 用户头像 -->
                        <div class="relative">
                            <button id="user-menu-button" class="flex items-center focus:outline-none">
                                <div class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                                    <i class="fa fa-user"></i>
                                </div>
                                <span class="ml-2 text-sm font-medium text-gray-700 hidden md:block">管理员</span>
                                <i class="fa fa-chevron-down ml-1 text-xs text-gray-400 hidden md:block"></i>
                            </button>
                            
                            <!-- 用户下拉菜单 -->
                            <div id="user-menu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20 hidden">
                                <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                                <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">设置</a>
                                <div class="border-t border-gray-100"></div>
                                <a href="login.html" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>
            
            <!-- 移动端侧边栏 -->
            <div id="mobile-sidebar" class="fixed inset-0 z-40 hidden">
                <div class="fixed inset-0 bg-gray-600 bg-opacity-75"></div>
                <div class="relative flex-1 flex flex-col max-w-xs w-full bg-white">
                    <div class="absolute top-0 right-0 -mr-12 pt-2">
                        <button id="close-sidebar-button" class="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white">
                            <i class="fa fa-times text-white"></i>
                        </button>
                    </div>
                    <div class="flex-1 h-0 pt-5 pb-4 overflow-y-auto">
                        <div class="flex-shrink-0 flex items-center justify-center">
                            <img src="https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/c70bc843c62648c5ac1442b15138cda2~tplv-a9rns2rl98-image.image?rcl=20251027174223B6A1FC2217E476B2DCF3&rk3s=8e244e95&rrcfp=f06b921b&x-expires=1764150165&x-signature=fvtwF014Si8DyDXCBMppvkase%2BI%3D" 
                                 alt="Property Management System Logo" 
                                 class="h-12 w-12">
                        </div>
                        <nav class="mt-5 px-2 space-y-1">
                            <a href="dashboard.html" class="nav-link" data-target="dashboard-section">
                                <i class="fa fa-dashboard"></i>
                                <span>控制面板</span>
                            </a>
                            <a href="community.html" class="nav-link" data-target="community-section">
                                <i class="fa fa-building"></i>
                                <span>小区管理</span>
                            </a>
                            <a href="owners.html" class="nav-link active" data-target="owners-section">
                                <i class="fa fa-users"></i>
                                <span>业主管理</span>
                            </a>
                            <a href="maintenance.html" class="nav-link" data-target="maintenance-section">
                                <i class="fa fa-wrench"></i>
                                <span>报修管理</span>
                            </a>
                            <a href="announcements.html" class="nav-link" data-target="announcements-section">
                                <i class="fa fa-bullhorn"></i>
                                <span>公告管理</span>
                            </a>
                            <a href="fee_management.html" class="nav-link" data-target="fee-management-section">
                                <i class="fa fa-credit-card"></i>
                                <span>物业收费管理</span>
                            </a>
                            <a href="settings.html" class="nav-link" data-target="settings-section">
                                <i class="fa fa-cog"></i>
                                <span>系统设置</span>
                            </a>
                        </nav>
                    </div>
                </div>
            </div>
            
            <!-- 页面内容 -->
            <main class="flex-1 overflow-y-auto p-6 bg-gray-50">
                <!-- 业主管理 -->
                <section id="owners-section" class="space-y-6">
                    <div class="flex items-center justify-between">
                        <h1 class="text-2xl font-bold text-gray-800">业主管理</h1>
                        <button id="add-owner-button" class="btn btn-primary">
                            <i class="fa fa-plus mr-2"></i>
                            添加业主
                        </button>
                    </div>
                    
                    <!-- 业主列表 -->
                    <div class="card">
                        <div class="card-header">
                            <h3>业主列表</h3>
                            <div class="flex items-center space-x-2">
                                <div class="relative">
                                    <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                        <i class="fa fa-search text-gray-400"></i>
                                    </span>
                                    <input type="text" placeholder="搜索业主..." class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <select class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="">选择小区</option>
                                    <option value="sunshine">阳光花园</option>
                                    <option value="harmony">和谐家园</option>
                                    <option value="happiness">幸福小区</option>
                                </select>
                            </div>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">性别</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所在小区</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">楼栋单元</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房间号</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住状态</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <tr class="table-row-hover">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm font-medium text-gray-900">张三</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            男
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            13800138000
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            阳光花园
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            1号楼1单元
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            101室
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="badge badge-success">已入住</span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <a href="#" class="text-blue-600 hover:text-blue-900 mr-3">查看</a>
                                            <a href="#" class="text-green-600 hover:text-green-900 mr-3">编辑</a>
                                            <a href="#" class="text-red-600 hover:text-red-900">删除</a>
                                        </td>
                                    </tr>
                                    <tr class="table-row-hover">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm font-medium text-gray-900">李四</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            女
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            13900139000
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            和谐家园
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            3号楼2单元
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            202室
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="badge badge-success">已入住</span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <a href="#" class="text-blue-600 hover:text-blue-900 mr-3">查看</a>
                                            <a href="#" class="text-green-600 hover:text-green-900 mr-3">编辑</a>
                                            <a href="#" class="text-red-600 hover:text-red-900">删除</a>
                                        </td>
                                    </tr>
                                    <tr class="table-row-hover">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm font-medium text-gray-900">王五</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            男
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            13700137000
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            幸福小区
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            2号楼1单元
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            301室
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="badge badge-warning">未入住</span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <a href="#" class="text-blue-600 hover:text-blue-900 mr-3">查看</a>
                                            <a href="#" class="text-green-600 hover:text-green-900 mr-3">编辑</a>
                                            <a href="#" class="text-red-600 hover:text-red-900">删除</a>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="px-6 py-4 border-t border-gray-200">
                            <div class="flex items-center justify-between">
                                <div class="text-sm text-gray-700">
                                    显示 <span class="font-medium">1</span> 到 <span class="font-medium">3</span> 共 <span class="font-medium">10</span> 条结果
                                </div>
                                <div class="flex space-x-2">
                                    <button class="btn btn-sm btn-outline" disabled>
                                        <i class="fa fa-chevron-left"></i>
                                    </button>
                                    <button class="btn btn-sm btn-primary">1</button>
                                    <button class="btn btn-sm btn-outline">2</button>
                                    <button class="btn btn-sm btn-outline">3</button>
                                    <button class="btn btn-sm btn-outline">4</button>
                                    <button class="btn btn-sm btn-outline">
                                        <i class="fa fa-chevron-right"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 移动端菜单按钮
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileSidebar = document.getElementById('mobile-sidebar');
            const closeSidebarButton = document.getElementById('close-sidebar-button');
            
            mobileMenuButton.addEventListener('click', function() {
                mobileSidebar.classList.remove('hidden');
            });
            
            closeSidebarButton.addEventListener('click', function() {
                mobileSidebar.classList.add('hidden');
            });
            
            // 用户菜单切换
            const userMenuButton = document.getElementById('user-menu-button');
            const userMenu = document.getElementById('user-menu');
            
            userMenuButton.addEventListener('click', function() {
                userMenu.classList.toggle('hidden');
            });
            
            // 点击页面其他地方关闭下拉菜单
            document.addEventListener('click', function(event) {
                if (!userMenuButton.contains(event.target) && !userMenu.contains(event.target)) {
                    userMenu.classList.add('hidden');
                }
            });
            
        // 添加业主模态框逻辑
        const addOwnerButton = document.getElementById('add-owner-button');
        const addOwnerModal = document.getElementById('add-owner-modal');
        const closeOwnerModal = document.getElementById('close-owner-modal');
        const cancelAddOwner = document.getElementById('cancel-add-owner');
        const submitAddOwner = document.getElementById('submit-add-owner');
        const ownerPhone = document.getElementById('owner-phone');
        const phoneError = document.getElementById('phone-error');
        
        // 显示添加业主模态框
        addOwnerButton.addEventListener('click', function() {
            addOwnerModal.classList.remove('hidden');
            // 延迟加载小区列表确保模态框DOM已渲染
            setTimeout(function() {
                loadCommunities();
            }, 100);
        });
        
        // 加载小区列表
        window.loadCommunities = function() {
            console.log('loadCommunities function was called');
            // 获取两个社区下拉菜单元素
            const addCommunitySelect = document.getElementById('owner-community');
            const editCommunitySelect = document.getElementById('edit-owner-community');
            
            // 检查是否至少获取到了一个select元素
            if (!addCommunitySelect && !editCommunitySelect) {
                console.error('Could not find select elements with id owner-community or edit-owner-community');
                // Try to find all select elements to debug
                console.log('All select elements on page:', document.querySelectorAll('select'));
                return;
            }
            
            // 使用文档片段提高性能
            const fragment = document.createDocumentFragment();
            
            // 创建默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择小区';
            defaultOption.disabled = true;
            defaultOption.selected = true;
            fragment.appendChild(defaultOption);
            
            // 使用相对路径的API endpoint以避免CORS问题
            const apiUrl = '/api/communities/';
            console.log('Calling API URL:', apiUrl);
            console.log('Current window location:', window.location.href);
            
            // 调用API获取小区列表
            fetch(apiUrl, {
                credentials: 'include'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json(); // 直接获取JSON数据
            })
            .then(data => {
                // 处理Django REST framework的分页数据结构
                const communities = data.results || data;
                console.log('Decoded communities:', communities);
                
                // 为一个select元素创建并添加选项
                function populateSelect(selectElement) {
                    if (!selectElement) return;
                    
                    // 创建新的文档片段
                    const selectFragment = document.createDocumentFragment();
                    
                    // 创建默认选项
                    const defaultOption = document.createElement('option');
                    defaultOption.value = '';
                    defaultOption.textContent = '请选择小区';
                    defaultOption.disabled = true;
                    defaultOption.selected = true;
                    selectFragment.appendChild(defaultOption);
                    
                    // 添加所有社区选项
                    communities.forEach(community => {
                        const option = document.createElement('option');
                        option.value = community.id;
                        option.textContent = community.name;
                        selectFragment.appendChild(option);
                        console.log('Created option:', option);
                    });
                    
                    // 清空现有的所有选项
                    while (selectElement.firstChild) {
                        selectElement.removeChild(selectElement.firstChild);
                    }
                    
                    // 将文档片段中的所有选项添加到select元素
                    selectElement.appendChild(selectFragment);
                    
                    // 确保select元素可见
                    selectElement.style.display = 'block';
                    
                    // 调试：显示当前所有选项
                    console.log('Current options in select:', Array.from(selectElement.options));
                }
                
                // 填充添加业主表单和编辑业主表单的社区下拉菜单
                populateSelect(addCommunitySelect);
                populateSelect(editCommunitySelect);
            })
            .catch(error => {
                console.error('加载小区列表失败:', error);
                showNotification('加载小区列表失败，请重试', 'error');
            });
        }
        
        // 关闭添加业主模态框
        function hideOwnerModal() {
            addOwnerModal.classList.add('hidden');
            // 重置表单和错误提示
            document.getElementById('add-owner-form').reset();
            phoneError.classList.add('hidden');
            // 移除所有错误样式
            const inputs = document.querySelectorAll('#add-owner-form input, #add-owner-form select');
            inputs.forEach(input => {
                input.classList.remove('border-red-500');
            });
        }
        
        closeOwnerModal.addEventListener('click', hideOwnerModal);
        cancelAddOwner.addEventListener('click', hideOwnerModal);
        
        // 点击模态框背景关闭
        addOwnerModal.addEventListener('click', function(event) {
            if (event.target === addOwnerModal) {
                hideOwnerModal();
            }
        });
        
        // 表单验证函数
    function validateForm() {
        let isValid = true;
        
        // 验证必填字段
        const requiredFields = document.querySelectorAll('#add-owner-form [required]');
        requiredFields.forEach(field => {
            if (field.tagName === 'INPUT' && field.type === 'radio') {
                // 检查单选按钮组是否有选中项
                const radioGroup = document.querySelectorAll(`input[name="${field.name}"]`);
                const isChecked = Array.from(radioGroup).some(radio => radio.checked);
                if (!isChecked) {
                    isValid = false;
                    // 为单选按钮组添加错误提示（通过父元素）
                    const parentDiv = field.closest('.space-y-2');
                    if (parentDiv) {
                        // 查找标签添加红色样式
                        const label = parentDiv.querySelector('label');
                        if (label) {
                            label.classList.add('text-red-500');
                        }
                    }
                } else {
                    // 移除错误样式
                    const parentDiv = field.closest('.space-y-2');
                    if (parentDiv) {
                        const label = parentDiv.querySelector('label');
                        if (label) {
                            label.classList.remove('text-red-500');
                        }
                    }
                }
            } else {
                // 常规字段验证
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('border-red-500');
                } else {
                    field.classList.remove('border-red-500');
                }
            }
        });
        
        // 验证手机号码格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (ownerPhone.value.trim()) {
            if (!phoneRegex.test(ownerPhone.value.trim())) {
                isValid = false;
                ownerPhone.classList.add('border-red-500');
                phoneError.classList.remove('hidden');
            } else {
                ownerPhone.classList.remove('border-red-500');
                phoneError.classList.add('hidden');
            }
        }
        
        // 验证身份证号格式
        const idCard = document.getElementById('owner-id-card');
        const idCardError = document.getElementById('id-card-error');
        if (idCard && idCard.value.trim()) {
            const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
            if (!idCardRegex.test(idCard.value.trim())) {
                isValid = false;
                idCard.classList.add('border-red-500');
                if (idCardError) {
                    idCardError.classList.remove('hidden');
                }
            } else {
                idCard.classList.remove('border-red-500');
                if (idCardError) {
                    idCardError.classList.add('hidden');
                }
            }
        }
        
        // 返回验证结果
        return isValid;
        
        return isValid;
    }
        
        // 实时验证手机号码
        ownerPhone.addEventListener('input', function() {
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (this.value.trim()) {
                if (!phoneRegex.test(this.value.trim())) {
                    this.classList.add('border-red-500');
                    phoneError.classList.remove('hidden');
                } else {
                    this.classList.remove('border-red-500');
                    phoneError.classList.add('hidden');
                }
            } else {
                this.classList.remove('border-red-500');
                phoneError.classList.add('hidden');
            }
        });
        
        // 为所有输入字段添加失去焦点时的验证
        const inputs = document.querySelectorAll('#add-owner-form input, #add-owner-form select');
        inputs.forEach(input => {
            if (input.type !== 'radio') {
                input.addEventListener('blur', function() {
                    if (this.hasAttribute('required')) {
                        if (!this.value.trim()) {
                            this.classList.add('border-red-500');
                        } else {
                            this.classList.remove('border-red-500');
                            // 特别验证手机号和身份证号
                            if (this.id === 'owner-phone') {
                                const phoneRegex = /^1[3-9]\d{9}$/;
                                if (phoneRegex.test(this.value.trim())) {
                                    phoneError.classList.add('hidden');
                                } else {
                                    phoneError.classList.remove('hidden');
                                }
                            } else if (this.id === 'owner-id-card') {
                                const idCardError = document.getElementById('id-card-error');
                                const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
                                if (idCardError) {
                                    if (idCardRegex.test(this.value.trim())) {
                                        idCardError.classList.add('hidden');
                                    } else {
                                        idCardError.classList.remove('hidden');
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
        
        // 提交表单事件处理
        document.getElementById('submit-add-owner').addEventListener('click', function() {
            // 表单验证
            if (!validateForm()) {
                return;
            }
            
            const form = document.getElementById('add-owner-form');
            const formData = new FormData(form);
            const data = {};
            
            // 将FormData转换为JSON对象
            formData.forEach((value, key) => {
                data[key] = value;
            });
            
            // 转换数据格式以匹配后端模型
            data.gender = data.gender === '男' ? 'male' : 'female';
            data.community = parseInt(data.community, 10);
            data.is_active = data.status === '已入住' ? true : false;
            
            // 调试：查看发送的数据
            console.log('发送的业主数据:', data);
            // 查看FormData中的所有字段
            console.log('FormData中的所有字段:');
            formData.forEach((value, key) => {
                console.log(`${key}: ${value}`);
            });
            
            // 发送API请求
            fetch('http://127.0.0.1:8000/api/owners/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCSRFToken()
                },
                credentials: 'include',
                body: JSON.stringify(data)
            })
            .then(response => {
                console.log('响应状态:', response.status);
                if (!response.ok) {
                    // 非成功响应，获取详细错误信息
                    return response.text().then(text => {
                        try {
                            const errorData = JSON.parse(text);
                            return Promise.reject(new Error(`添加失败: ${JSON.stringify(errorData)}`));
                        } catch {
                            return Promise.reject(new Error(`添加失败: ${text}`));
                        }
                    });
                }
                return response.json();
            })
            .then(result => {
                console.log('响应结果:', result);
                console.log('响应结果类型:', typeof result);
                console.log('响应结果是否包含id:', result.id !== undefined);
                console.log('响应结果id值:', result.id);
                if (result.id) {
                    // 添加成功
                    console.log('添加成功，准备刷新页面');
                    alert('业主添加成功');
                    // 关闭模态框
                    document.getElementById('add-owner-modal').classList.add('hidden');
                    // 刷新页面
                    location.reload();
                } else {
                    // 处理错误
                    console.log('添加失败: 没有id字段');
                    alert('添加失败: ' + JSON.stringify(result));
                }
            })
            .catch(error => {
                console.error('添加业主失败:', error);
                alert(`添加失败: ${error.message}`);
            });
        });
        
        // 为取消按钮添加事件监听
        cancelAddOwner.addEventListener('click', function() {
            hideOwnerModal();
        });
        
        // 为关闭按钮添加事件监听
        closeOwnerModal.addEventListener('click', function() {
            hideOwnerModal();
        });
        
        // 初始化时从后端加载业主列表
        updateOwnerList();
    }); // 闭合DOMContentLoaded监听器
    
    // 隐藏业主添加模态框函数
    function hideOwnerModal() {
        const modal = document.getElementById('add-owner-modal');
        if (modal) {
            modal.classList.add('hidden');
            // 重置表单
            if (document.getElementById('add-owner-form')) {
                document.getElementById('add-owner-form').reset();
            }
            // 隐藏可能的错误提示
            if (document.getElementById('phone-error')) {
                document.getElementById('phone-error').classList.add('hidden');
            }
            if (document.getElementById('id-card-error')) {
                document.getElementById('id-card-error').classList.add('hidden');
            }
            // 移除所有输入框的错误样式
            const inputs = document.querySelectorAll('#add-owner-form input, #add-owner-form select');
            inputs.forEach(input => {
                input.classList.remove('border-red-500');
            });
        }
    }
    
    // 真实API调用函数（发送请求到后端保存数据）
    function simulateApiCall(data) {
        // 转换数据格式以匹配后端模型
        const ownerData = {
            name: data.name,
            gender: data.gender === '男' ? 'male' : 'female',
            phone: data.phone,
            id_card: data.id_card, // 使用表单输入的身份证号
            community: parseInt(document.getElementById('owner-community').value, 10), // 使用选择的小区ID
            building: data.building,
            unit: data.unit, // 使用表单输入的单元
            room_number: data.room_number,
            house_area: 0,
            is_active: data.status === '已入住' ? true : false
        };
        
        console.log('发送的数据:', ownerData);
        const csrfToken = getCSRFToken();
        console.log('CSRF令牌:', csrfToken);
        
        return fetch('http://127.0.0.1:8000/api/owners/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken,
                'Accept': 'application/json'
            },
            credentials: 'include', // 包含cookie以保持会话
            body: JSON.stringify(ownerData)
        }).then(response => {
            console.log('响应状态:', response.status, response.statusText);
            if (!response.ok) {
                return response.json().then(errorData => {
                    console.log('错误详情:', errorData);
                    throw new Error(errorData.detail || JSON.stringify(errorData) || '添加失败');
                }).catch(() => {
                    throw new Error('添加失败，请检查网络连接和服务器日志');
                });
            }
            return response.json();
        }).catch(error => {
            console.error('API调用错误:', error);
            throw error;
        });
    }
    
    // 获取CSRF令牌
    function getCSRFToken() {
        let csrfToken = '';
        const cookies = document.cookie.split(';');
        for (const cookie of cookies) {
            const [name, value] = cookie.trim().split('=');
            if (name === 'csrftoken') {
                csrfToken = decodeURIComponent(value);
                break;
            }
        }
        return csrfToken;
    }
    
    // 显示通知函数（全局定义，以便在DOMContentLoaded内访问）
    function showNotification(message, type = 'info') {
        // 检查是否已存在通知元素，如果存在则移除
        const existingNotification = document.getElementById('notification');
        if (existingNotification) {
            existingNotification.remove();
        }
        
        // 创建通知元素
        const notification = document.createElement('div');
        notification.id = 'notification';
        
        // 设置样式和内容
        const bgColor = type === 'success' ? 'bg-green-500' : 
                       type === 'error' ? 'bg-red-500' : 'bg-blue-500';
        
        notification.className = `fixed top-4 right-4 px-4 py-3 rounded-md shadow-lg text-white ${bgColor} transform transition-all duration-300 ease-in-out z-50`;
        notification.innerHTML = `
            <div class="flex items-center">
                <i class="fa fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
                <span>${message}</span>
            </div>
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 自动移除通知
        setTimeout(() => {
            notification.classList.add('opacity-0', 'translate-y-[-10px]');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    // 从后端获取最新的业主列表并更新表格
    function updateOwnerList() {
        // 获取表格体
        const tableBody = document.querySelector('table tbody');
        if (!tableBody) return;
        
        // 清空表格内容（除了表头）
        tableBody.innerHTML = '';
        
        // 显示加载状态
        const loadingRow = document.createElement('tr');
        loadingRow.innerHTML = `
            <td colspan="8" class="px-6 py-4 text-center">
                <div class="flex justify-center items-center">
                    <i class="fa fa-spinner fa-spin mr-2"></i>
                    <span>加载中...</span>
                </div>
            </td>
        `;
        tableBody.appendChild(loadingRow);
        
        // 从后端API获取业主数据
        fetch('/api/owners/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken(),
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache'
            },
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取业主列表失败');
            }
            return response.json();
        })
        .then(data => {
            // 清空表格
            tableBody.innerHTML = '';
            
            // 处理Django REST framework的分页数据结构
            window.owners = data.results || data;
            
            // 检查是否有数据
            if (window.owners.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                    <td colspan="8" class="px-6 py-4 text-center text-gray-500">
                        暂无业主数据
                    </td>
                `;
                tableBody.appendChild(emptyRow);
                return;
            }
            
            // 添加所有业主数据到表格
            window.owners.forEach(owner => {
                const newRow = document.createElement('tr');
                newRow.className = 'bg-white border-b hover:bg-gray-50 transition-colors duration-150';
                // 添加业主ID到行数据
                newRow.dataset.id = owner.id;
                
                // 设置状态样式
                const statusClass = owner.is_active ? 
                    'px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded' : 
                    'px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded';
                
                // 设置表格行内容
                newRow.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900">${owner.name}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-500">${owner.gender === 'male' ? '男' : '女'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-500">${owner.phone}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-500">${owner.community_name || '-'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-500">${owner.building}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-500">${owner.room_number}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="${statusClass}">${owner.is_active ? '已激活' : '未激活'}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <a href="#" class="text-blue-600 hover:text-blue-900 mr-3">查看</a>
                        <a href="#" class="text-blue-600 hover:text-blue-900 mr-3 owner-edit-btn">编辑</a>
                        <a href="#" class="text-red-600 hover:text-red-900">删除</a>
                    </td>`;
                
                // 添加行到表格
                tableBody.appendChild(newRow);
                
                // 绑定操作事件
                bindActionEvents(newRow);
            });
        })
        .catch(error => {
            console.error('获取业主列表失败:', error);
            // 更新加载提示为错误信息
            tableBody.innerHTML = '';
            const errorRow = document.createElement('tr');
            errorRow.innerHTML = `
                <td colspan="8" class="px-6 py-4 text-center text-red-500">
                    获取数据失败，请稍后重试
                </td>
            `;
            tableBody.appendChild(errorRow);
        });
    }
    
    // 更新结果数量显示
    function updateResultCount() {
        const resultTextElement = document.querySelector('.flex.justify-between.items-center');
        if (resultTextElement) {
            // 提取当前文本中的数字
            const currentText = resultTextElement.textContent;
            const matches = currentText.match(/显示\s+([0-9]+)\s+到\s+([0-9]+)\s+共\s+([0-9]+)\s+条结果/);
            
            if (matches && matches.length === 4) {
                // 解析数字
                let startNum = parseInt(matches[1], 10);
                let endNum = parseInt(matches[2], 10);
                let totalNum = parseInt(matches[3], 10) + 1; // 增加1条新记录
                
                // 如果当前显示的是第一页，增加结束数字
                if (startNum === 1) {
                    endNum += 1;
                }
                
                // 更新文本
                resultTextElement.innerHTML = `<span>显示 ${startNum} 到 ${endNum} 共 ${totalNum} 条结果</span>`;
            }
        }
    }
    
    // 为操作按钮绑定事件
     function bindActionEvents(rowElement) {
         const actionLinks = rowElement.querySelectorAll('td:last-child a');
         actionLinks.forEach(link => {
             link.addEventListener('click', function(e) {
                 e.preventDefault();
                 const action = this.textContent.trim();
                 const ownerName = this.closest('tr').querySelector('td:first-child div').textContent;
                 
                 if (action === '删除') {
                     if (confirm(`确定要删除业主「${ownerName}」吗？`)) {
                         // 模拟删除操作
                         const row = this.closest('tr');
                         row.style.opacity = '0';
                         row.style.height = row.offsetHeight + 'px';
                          
                         setTimeout(() => {
                             row.style.height = '0';
                             row.style.padding = '0';
                             row.style.margin = '0';
                             row.style.overflow = 'hidden';
                             row.style.transition = 'all 0.3s ease';
                               
                             setTimeout(() => {
                                 row.remove();
                                 // 更新结果数量
                                 updateResultCount();
                                 showNotification('业主删除成功', 'success');
                             }, 300);
                         }, 300);
                     }
                 } else if (action === '查看') {
                     // 获取业主ID
                     const row = this.closest('tr');
                     const ownerId = parseInt(row.dataset.id);
                     
                     // 查找业主数据
                     const owner = window.owners.find(o => o.id === ownerId);
                     if (owner) {
                         // 填充模态框数据
                         document.getElementById('view-owner-name').textContent = owner.name;
                         document.getElementById('view-owner-gender').textContent = owner.gender === 'male' ? '男' : '女';
                         document.getElementById('view-owner-phone').textContent = owner.phone;
                         document.getElementById('view-owner-id-card').textContent = owner.id_card;
                         document.getElementById('view-owner-community').textContent = owner.community_name || '-';
                         document.getElementById('view-owner-building').textContent = owner.building;
                         document.getElementById('view-owner-unit').textContent = owner.unit;
                         document.getElementById('view-owner-room').textContent = owner.room_number;
                         document.getElementById('view-owner-status').textContent = owner.is_active ? '已激活' : '未激活';
                         
                         // 显示模态框
                         document.getElementById('view-owner-modal').classList.remove('hidden');
                     }
                 }
             });
         });
     }
    </script>
    
    <!-- 添加业主模态框 -->
    <div id="add-owner-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
            <!-- 背景遮罩 -->
            <div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"></div>
            
            <!-- 模态框内容 -->
            <div class="relative inline-block w-full max-w-md my-8 overflow-hidden text-left transition-all transform bg-white rounded-lg shadow-xl">
                <!-- 模态框头部 -->
                <div class="px-6 py-4 border-b border-gray-200">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-medium text-gray-900">添加业主</h3>
                        <button id="close-owner-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 模态框表单 -->
                <form id="add-owner-form" class="px-6 py-4 space-y-4">
                    <div class="space-y-2">
                        <label for="owner-name" class="block text-sm font-medium text-gray-700">姓名 <span class="text-red-500">*</span></label>
                        <input type="text" id="owner-name" name="name" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    
                    <div class="space-y-2">
                        <label class="block text-sm font-medium text-gray-700">性别 <span class="text-red-500">*</span></label>
                        <div class="flex items-center space-x-4">
                            <label class="flex items-center">
                                <input type="radio" name="gender" value="男" required 
                                       class="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500">
                                <span class="ml-2 text-sm text-gray-700">男</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="gender" value="女" 
                                       class="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500">
                                <span class="ml-2 text-sm text-gray-700">女</span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-phone" class="block text-sm font-medium text-gray-700">联系电话 <span class="text-red-500">*</span></label>
                        <input type="tel" id="owner-phone" name="phone" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <p class="hidden text-red-500 text-xs" id="phone-error">请输入正确的手机号码</p>
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-id-card" class="block text-sm font-medium text-gray-700">身份证号 <span class="text-red-500">*</span></label>
                        <input type="text" id="owner-id-card" name="id_card" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <p class="hidden text-red-500 text-xs" id="id-card-error">请输入正确的18位身份证号</p>
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-community" class="block text-sm font-medium text-gray-700">所在小区 <span class="text-red-500">*</span></label>
                        <select id="owner-community" name="community" required 
                                class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">请选择小区</option>
                        </select>
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-building" class="block text-sm font-medium text-gray-700">楼栋 <span class="text-red-500">*</span></label>
                        <input type="text" id="owner-building" name="building" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="请输入楼栋号">
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-unit" class="block text-sm font-medium text-gray-700">单元 <span class="text-red-500">*</span></label>
                        <input type="text" id="owner-unit" name="unit" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="请输入单元">
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-room" class="block text-sm font-medium text-gray-700">房间号 <span class="text-red-500">*</span></label>
                        <input type="text" id="owner-room" name="room_number" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="请输入房间号">
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-house-area" class="block text-sm font-medium text-gray-700">房屋面积 <span class="text-red-500">*</span></label>
                        <input type="number" id="owner-house-area" name="house_area" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="请输入房屋面积" step="0.01">
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-move-in-date" class="block text-sm font-medium text-gray-700">入住日期 <span class="text-red-500">*</span></label>
                        <input type="date" id="owner-move-in-date" name="move_in_date" required 
                               class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    
                    <div class="space-y-2">
                        <label for="owner-status" class="block text-sm font-medium text-gray-700">入住状态 <span class="text-red-500">*</span></label>
                        <select id="owner-status" name="status" required 
                                class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="已入住">已入住</option>
                            <option value="未入住">未入住</option>
                        </select>
                    </div>
                </form>
                
                <!-- 模态框底部按钮 -->
                <div class="flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 px-6 py-4 bg-gray-50 border-t border-gray-200 sm:flex-nowrap">
                    <button id="cancel-add-owner" class="inline-flex justify-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        取消
                    </button>
                    <button id="submit-add-owner" class="inline-flex justify-center px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        添加
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看业主详情模态框 -->
    <div id="view-owner-modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <!-- 模态框背景 -->
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>

            <!-- 模态框内容 -->
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <!-- 模态框头部 -->
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="view-owner-title">
                        业主详情
                    </h3>
                    <div class="mt-2">
                        <!-- 业主详情信息 -->
                        <div class="grid grid-cols-1 gap-4">
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">姓名</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-name"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">性别</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-gender"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">联系电话</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-phone"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">身份证号</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-id-card"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">所在小区</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-community"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">楼栋</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-building"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">单元</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-unit"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">房间号</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-room"></div>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">入住状态</div>
                                <div class="text-base font-medium text-gray-900" id="view-owner-status"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 模态框底部按钮 -->
                <div class="flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 px-6 py-4 bg-gray-50 border-t border-gray-200 sm:flex-nowrap">
                    <button id="close-view-owner" class="inline-flex justify-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" onclick="document.getElementById('view-owner-modal').classList.add('hidden')">
                        关闭
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑业主模态框 -->
    <div id="edit-owner-modal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="edit-owner-modal-title" role="dialog" aria-modal="true">
        <!-- 背景遮罩 -->
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>

        <!-- 模态框内容 -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <!-- 模态框头部 -->
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900" id="edit-owner-modal-title">
                    编辑业主信息
                </h3>
                <div class="mt-2">
                    <!-- 业主详情信息 -->
                    <form id="edit-owner-form">
                        <!-- 隐藏的业主ID字段 -->
                        <input type="hidden" id="edit-owner-id">
                        <div class="grid grid-cols-1 gap-4">
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">姓名</div>
                                <input type="text" id="edit-owner-name" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">性别</div>
                                <select id="edit-owner-gender" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">联系电话</div>
                                <input type="tel" id="edit-owner-phone" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">身份证号</div>
                                <input type="text" id="edit-owner-id-card" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">所在小区</div>
                                <select id="edit-owner-community" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option value="">请选择小区</option>
                                    <!-- JavaScript生成小区选项 -->
                                </select>
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">楼栋</div>
                                <input type="text" id="edit-owner-building" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                       placeholder="请输入楼栋">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">单元</div>
                                <input type="text" id="edit-owner-unit" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                       placeholder="请输入单元">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">房间号</div>
                                <input type="text" id="edit-owner-room" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                       placeholder="请输入房间号">
                            </div>
                            <div class="p-3 bg-gray-50 rounded-md">
                                <div class="text-sm font-medium text-gray-500">入住状态</div>
                                <select id="edit-owner-status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <option value="已激活">已激活</option>
                                    <option value="未激活">未激活</option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <!-- 模态框底部按钮 -->
            <div class="flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 px-6 py-4 bg-gray-50 border-t border-gray-200 sm:flex-nowrap">
                <button id="close-edit-owner" class="inline-flex justify-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" onclick="document.getElementById('edit-owner-modal').classList.add('hidden')">
                    取消
                </button>
                <button id="save-edit-owner" class="inline-flex justify-center px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-blue-600 rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    保存
                </button>
            </div>
        </div>
    </div>

    <script>
        // 业主数据数组
        const owners = [
            { name: "张三", gender: "男", phone: "1306302560", idCard: "123456789012345678", community: "海经贸", building: "2", unit: "2", room_number: "27", status: "已激活" },
            { name: "张三", gender: "女", phone: "1306302560", idCard: "876543210987654321", community: "111", building: "2", unit: "2", room_number: "27", status: "已激活" },
            { name: "张三", gender: "男", phone: "1306302560", idCard: "1357924680135792", community: "11", building: "2", unit: "2", room_number: "27", status: "未激活" },
            { name: "张三", gender: "男", phone: "1306302560", idCard: "2468135790246813", community: "海经贸", building: "2", unit: "2", room_number: "27", status: "未激活" },
            { name: "王五", gender: "男", phone: "13086035620", idCard: "567890123456789012", community: "测试", building: "5", unit: "5", room_number: "01", status: "已激活" }
        ];
        

        // 业主编辑功能
        const editModal = document.getElementById('edit-owner-modal');
        const closeEditModal = document.getElementById('close-edit-owner');
        const saveEditModal = document.getElementById('save-edit-owner');
        const editOwnerForm = document.getElementById('edit-owner-form');

        // 保存当前编辑的业主ID
        let currentEditOwnerId = null;

        // 为每个编辑按钮添加点击事件
        function bindEditEvents() {
            // 先移除旧的事件监听（如果有）
            const editButtons = document.querySelectorAll('.owner-edit-btn');
            editButtons.forEach(button => {
                button.replaceWith(button.cloneNode(true));
            });

            // 重新添加事件监听
            document.querySelectorAll('.owner-edit-btn').forEach(button => {
                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    const row = button.closest('tr');
                    const ownerId = parseInt(row.dataset.id, 10);
                    const owners = window.owners || [];
                    const owner = owners.find(o => o.id === ownerId);

                    if (owner) {
                        currentEditOwnerId = ownerId;
                        // 显示编辑模态框
                        editModal.classList.remove('hidden');
                        // 延迟加载小区列表确保模态框DOM已渲染
                        setTimeout(() => {
                            // 填充编辑表单
                            document.getElementById('edit-owner-id').value = owner.id;
                            document.getElementById('edit-owner-name').value = owner.name;
                            // Map backend gender value to front-end display value
                        const genderDisplayValue = owner.gender === 'male' ? '男' : '女';
                        document.getElementById('edit-owner-gender').value = genderDisplayValue;
                            document.getElementById('edit-owner-phone').value = owner.phone;
                            document.getElementById('edit-owner-id-card').value = owner.id_card;
                            document.getElementById('edit-owner-building').value = owner.building;
                            document.getElementById('edit-owner-unit').value = owner.unit;
                            document.getElementById('edit-owner-room').value = owner.room_number;
                            document.getElementById('edit-owner-status').value = owner.is_active ? '已激活' : '未激活';
                            // 加载社区下拉菜单
                            loadCommunities();
                            // 设置社区值
                            setTimeout(() => {
                                document.getElementById('edit-owner-community').value = owner.community;
                            }, 200);
                        }, 100);
                    }
                });
            });
        }

        // 点击模态框背景关闭模态框
        editModal.addEventListener('click', (e) => {
            if (e.target === editModal) {
                editModal.classList.add('hidden');
            }
        });

        // 保存编辑内容
        saveEditModal.addEventListener('click', () => {
            editOwnerForm.dispatchEvent(new Event('submit'));
        });

        // 编辑表单提交处理
        editOwnerForm.addEventListener('submit', (e) => {
            e.preventDefault();
            if (!currentEditOwnerId) return;

            // 获取表单数据
            const updatedOwner = {
                name: document.getElementById('edit-owner-name').value,
                // Map front-end display value to backend expected value
                gender: document.getElementById('edit-owner-gender').value === '男' ? 'male' : 'female',
                phone: document.getElementById('edit-owner-phone').value,
                id_card: document.getElementById('edit-owner-id-card').value,
                community: parseInt(document.getElementById('edit-owner-community').value, 10),
                building: document.getElementById('edit-owner-building').value,
                unit: document.getElementById('edit-owner-unit').value,
                room_number: document.getElementById('edit-owner-room').value,
                is_active: document.getElementById('edit-owner-status').value === '已激活'
            };


            // 发送PUT请求更新业主信息
            fetch(`/api/owners/${currentEditOwnerId}/`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCSRFToken(),
                    'Accept': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(updatedOwner)
            })
            .then(response => {
                console.log('响应状态:', response.status, response.statusText);
                if (!response.ok) {
                    // 如果响应不是ok的，解析错误信息
                    return response.json().then(errorData => {
                        console.log('错误详情:', errorData);
                        throw new Error(errorData.detail || JSON.stringify(errorData) || '更新失败');
                    }).catch(() => {
                        // 如果解析JSON失败，使用默认错误信息
                        throw new Error('更新失败，请检查网络连接和服务器日志');
                    });
                }
                // 检查响应是否有内容
                const contentType = response.headers.get('Content-Type');
                if (contentType && contentType.includes('application/json')) {
                    return response.json();
                }
                return null; // 无响应体时返回null
            })
            .then(result => {
                // 更新成功，关闭模态框并刷新列表
                editModal.classList.add('hidden');
                updateOwnerList();
                showNotification('业主信息更新成功', 'success');
            })
            .catch(error => {
                console.error('更新失败:', error);
                showNotification('业主信息更新失败，请稍后重试', 'error');
            });
        });

        // 在updateOwnerList之后绑定事件
        const originalUpdateOwnerList = window.updateOwnerList;
        window.updateOwnerList = function() {
            const result = originalUpdateOwnerList.apply(this, arguments);
            // 延迟绑定事件，确保DOM已更新
            setTimeout(bindEditEvents, 100);
            return result;
        };

        // 初始化时绑定事件
        updateOwnerList();
    </script>
</body>
</html>